package com.lc.ibps.platform.rest.org;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lc.ibps.api.base.query.QueryFilter;
import com.lc.ibps.api.base.query.QueryOP;
import com.lc.ibps.api.org.constant.PartyType;
import com.lc.ibps.api.org.constant.UserStatus;
import com.lc.ibps.api.org.service.IPartyAttrQueryService;
import com.lc.ibps.api.org.service.IPartyEmployeeService;
import com.lc.ibps.api.org.service.IPartyLevelQueryService;
import com.lc.ibps.api.org.service.IPartyOrgService;
import com.lc.ibps.api.org.service.IPartyPositionService;
import com.lc.ibps.api.org.service.IPartyUserBaseQueryService;
import com.lc.ibps.base.core.constants.StringPool;
import com.lc.ibps.base.core.util.AppUtil;
import com.lc.ibps.base.core.util.BeanUtils;
import com.lc.ibps.base.core.util.string.StringUtil;
import com.lc.ibps.base.web.context.ContextUtil;
import com.lc.ibps.cloud.entity.APIPageList;
import com.lc.ibps.cloud.entity.APIRequest;
import com.lc.ibps.cloud.entity.APIResult;
import com.lc.ibps.org.party.builder.PartyEntityBuilder;
import com.lc.ibps.org.party.persistence.entity.PartyAttrPo;
import com.lc.ibps.org.party.persistence.entity.PartyEmployeePo;
import com.lc.ibps.org.party.persistence.entity.PartyLevelPo;
import com.lc.ibps.org.party.persistence.entity.PartyOrgPo;
import com.lc.ibps.org.party.persistence.entity.PartyPositionPo;
import com.lc.ibps.org.party.persistence.entity.PartyUserPo;
import com.lc.ibps.org.party.repository.PartyEmployeeRepository;
import com.lc.ibps.web.controller.BaseApiController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 
 *员工服务
 * <pre> 
 * 构建组：ibps-platform-appapi
 * 作者：zhongjh
 * 邮箱：zjh20140614@163.com
 * 日期：2018年8月7日-下午2:20:28
 * 版权：广州流辰信息技术有限公司版权所有
 * </pre>
 */
@RequestMapping(value="/api/webapi/employeeService")
@Api(value = "/employeeService",tags="用户管理-员工服务")
@RestController
public class EmployeeController extends BaseApiController{
	
	private IPartyEmployeeService employeeService;
	private IPartyUserBaseQueryService partyUserBaseQueryService;
	private IPartyOrgService partyOrgService;
	private IPartyLevelQueryService partyLevelQueryService;
	private IPartyAttrQueryService partyAttrQueryService;
	private IPartyPositionService partyPositionService;
	private PartyEmployeeRepository partyEmployeeRepository;
	
	public EmployeeController(){
		employeeService = AppUtil.getBean(IPartyEmployeeService.class);
		partyUserBaseQueryService = AppUtil.getBean(IPartyUserBaseQueryService.class);
		partyOrgService = AppUtil.getBean(IPartyOrgService.class);
		partyLevelQueryService = AppUtil.getBean(IPartyLevelQueryService.class);
		partyAttrQueryService = AppUtil.getBean(IPartyAttrQueryService.class);
		partyPositionService = AppUtil.getBean(IPartyPositionService.class);
		partyEmployeeRepository = AppUtil.getBean(PartyEmployeeRepository.class);
	}
	
	@ApiOperation(value = "获取用户信息", notes = "获取用户信息")
	@RequestMapping(value="/get",method=RequestMethod.GET)
	public APIResult<Map<String, Object>> get(){
		APIResult<Map<String, Object>> result = new APIResult<Map<String, Object>>();
		String id = ContextUtil.getCurrentUserId();
		
		PartyEmployeePo partyEmployee = null;
		PartyUserPo partyUser = null;
		PartyOrgPo partyOrg = null;
		PartyLevelPo partyLevel = null;
		List<PartyAttrPo> partyAttrs = null;
		List<PartyPositionPo> partyPositions = new ArrayList<>();
		try {
			if(StringUtil.isNotEmpty(id)){
				partyEmployee = PartyEmployeePo.fromJsonString(employeeService.getWithOrgJson(id));
				partyUser = PartyUserPo.fromJsonString(partyUserBaseQueryService.getById(id));
				if(BeanUtils.isNotEmpty(partyEmployee) && StringUtil.isNotBlank(partyEmployee.getGroupID())){
					String data = partyOrgService.getByIdJson(partyEmployee.getGroupID());
					partyOrg = PartyOrgPo.fromJsonString(data);
					if(BeanUtils.isNotEmpty(partyOrg)) {
						data = partyLevelQueryService.get(partyOrg.getLevelID());
						partyLevel = PartyLevelPo.fromJsonString(data);
					}
					// 组织路径
					if(BeanUtils.isNotEmpty(partyOrg)) {
						partyOrg.setPathName(PartyEntityBuilder.buildPathName(partyOrg.getId()));
					}
					// 岗位
					if(StringUtil.isNotEmpty(partyEmployee.getPositions())){
						String[] positionIds = partyEmployee.getPositions().split(StringPool.COMMA);
						String poStr = null;
						for (String posId : positionIds) {
							poStr = partyPositionService.get(posId);
							if(StringUtil.isEmpty(poStr)){
								continue;
							}
							partyPositions.add(PartyPositionPo.fromJsonString(poStr));
						}
					}
				}
				
				String data = partyAttrQueryService.findByPartyTypeUserId4Get(PartyType.EMPLOYEE.getValue(), id);
				partyAttrs = PartyAttrPo.fromJsonArrayString(data);
			}
			
			UserStatus[] statuses = UserStatus.values();
			Map<String, Object> map = new HashMap<>();
			map.put("partyEmployee",partyEmployee); 
			map.put("partyUser",partyUser);
			map.put("partyOrg",partyOrg);
			map.put("partyPosition", partyPositions);
			map.put("partyLevel",partyLevel);
			map.put("partyAttrs",partyAttrs);
			map.put("statuses", statuses); 
			result.setData(map);
			result.setMessage("成功获取用户信息！");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "获取用户信息失败！", e);
		}
		
		return result;
	}
	
	@ApiOperation(value = "通讯录", notes = "获取用户列表")
	@RequestMapping(value="/listJson",method=RequestMethod.POST)
	public APIResult<APIPageList<PartyEmployeePo>> listJson(
			@ApiParam(name = "request", value = "传入查询请求json字符串", required = true) @RequestBody(required = true) APIRequest request) {
		APIResult<APIPageList<PartyEmployeePo>> result = new APIResult<>();
		QueryFilter queryFilter = getQuerFilter(request);
		try {
			//拓展属性过滤部分
//			Map<String,Object> attrParams = RequestUtil.getMapByProfix(request, "QA^");
//			if(BeanUtils.isNotEmpty(attrParams)){
//				String data = defaultPartyEntityService.findByAttrKeyValueJson(attrParams, PartyType.EMPLOYEE.getValue());
//				if(JacksonUtil.isNotJsonArray(data)){
//					return new PageJson(new PageList<PartyEmployeePo>());
//				}
//				List<String> ids = JacksonUtil.getDTOList(data, String.class);
//				if(BeanUtils.isEmpty(ids)){
//					return new PageJson(new PageList<PartyEmployeePo>());
//				}
//				queryFilter.addFilter("ID_", ids, QueryOP.IN);
//			}
			
			List<PartyEmployeePo> list = partyEmployeeRepository.queryWithOrg(queryFilter);
			for(PartyEmployeePo po : list){
				String groupId = po.getGroupID();
				if(StringUtil.isNotEmpty(groupId)){
					po.setOrgName(PartyEntityBuilder.buildPathName(groupId));
				}
			}
			
			APIPageList<PartyEmployeePo> pageList = getAPIPageList(list);
			result.setData(pageList);
			result.setMessage("获取用户列表成功！");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "获取用户列表失败！", e);
		}
		
		return result;
	}
	
	@ApiOperation(value = "获取用户", notes = "获取用户列表")
	@RequestMapping(value="/queryByOrgIdOrName",method=RequestMethod.POST)
	public APIResult<APIPageList<PartyEmployeePo>> queryByOrgIdOrName(
			@ApiParam(name = "request", value = "传入查询请求json字符串", required = true) @RequestBody(required = true) APIRequest request) {
		APIResult<APIPageList<PartyEmployeePo>> result = new APIResult<>();
		QueryFilter queryFilter = getQuerFilter(request);
		if(StringUtil.isNotEmpty(request.getParameter("name"))){
			queryFilter.addFilter("NAME_", "%"+request.getParameter("name")+"%", QueryOP.LIKE);
		}else if(StringUtil.isNotEmpty(request.getParameter("orgId"))){
			queryFilter.addFilter("GROUP_ID_", request.getParameter("orgId"), QueryOP.EQUAL);
//		}else if(StringUtil.isEmpty(request.getParameter("orgId"))){
//			queryFilter.addFilter("GROUP_ID_", QueryOP.IS_NULL);
		}
		try {
			List<PartyEmployeePo> list = partyEmployeeRepository.query(queryFilter);
			
			APIPageList<PartyEmployeePo> pageList = getAPIPageList(list);
			result.setData(pageList);
			result.setMessage("获取用户列表成功！");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "获取用户列表失败！", e);
		}
		
		return result;
	}

}
